BETWEEN 运算符选择给定范围内的值。值可以是数字、文本或日期。
BETWEEN 运算符选择包括开始值和结束值的数据。
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2
以下是“Products”表中的示例:
ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
---|---|---|---|---|---|
1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18.00 |
2 | Chang | 1 | 1 | 24 - 12 oz bottles | 19.00 |
3 | Aniseed Syrup | 1 | 2 | 12 - 550 ml bottles | 10.00 |
4 | Chef Anton's Cajun Seasoning | 2 | 2 | 48 - 6 oz jars | 22.00 |
5 | Chef Anton's Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
以下 SQL 语句选择价格在 10 到 20 之间的所有产品:
Run SQLSELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
要显示上一个示例范围之外的产品,请使用 NOT BETWEEN:
Run SQLSELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20
以下 SQL 语句选择价格在 10 到 20 之间的所有产品,同时不显示 CategoryID 1、2 或 3 的产品:
Run SQLSELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3)
以下 SQL 语句从 ProductName 中选择“Carnarvon Tigers”和“Mozzarella di Giovanni”之间的所有产品:
Run SQLSELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName
以下 SQL 语句从 ProductName 中选择“Carnarvon Tigers”和“Chef Anton's Cajun Seasoning”之间的所有产品:
Run SQLSELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Chartreuse verte'
ORDER BY ProductName
以下 SQL 语句从 ProductName 选择所有产品,而不是在“Carnarvon Tigers”和“Mozzarella di Giovanni”之间:
Run SQLSELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName
以下是表“Orders”(“订单”)中的示例:
ProductID | OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
---|---|---|---|---|---|
1 | 10248 | 90 | 5 | 1996-07-04 | 3 |
2 | 10249 | 81 | 6 | 1996-07-05 | 1 |
3 | 10250 | 34 | 4 | 1996-07-08 | 2 |
4 | 10251 | 84 | 3 | 1996-07-08 | 1 |
5 | 10252 | 76 | 4 | 1996-07-09 | 2 |
以下 SQL 语句从 OrderDate 中选择“01-July-1996”和“31-July-1996”之间的所有订单 (Orders):
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#
或者:
Run SQLSELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31'